<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="100px" class="menu-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="postForm.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="URL" prop="url">
            <el-input v-model="postForm.url" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="所属群组" prop="clusterid">
            <el-select
              v-model="postForm.clusterid"
              multiple
              placeholder="可多选"
              style="width:100%"
            >
              <el-option
                v-for="item in rolesOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="上传图标" prop="cover">
            <el-upload
              v-if="iconList.length < 1"
              :action="uploadUrl"
              :multiple="false"
              :limit="1"
              name="fies"
              :headers="{token}"
              :on-success="handleUploadSucc"
              :show-file-list="false"
              drag
              accept="image/jpeg,image/png,image/gif"
              class="drag-upload-wrapper"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>

            <ul class="thumb-img-list">
              <li
                v-for="(item, index) in iconList"
                :key="index"
                class="item"
              >
                <img :src="item.url" :alt="item.name" class="img">
                <div
                  class="el-icon-close close-btn"
                  title="点击可删除"
                  @click="handleUploadRemove(item)"
                />
              </li>
            </ul>
            <!-- <input v-model="postForm.cover" type="hidden"> -->
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getRolesList
} from '@/api/roles'
import {
  getMenuList,
  addMenu,
  editMenu
} from '@/api/menu'

const defaultForm = {
  id: undefined,
  name: '',
  url: '',
  icon: ''
}

export default {
  name: 'MenuSettingForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rolesOptions: [],
      iconList: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入菜单URL', trigger: 'blur' }
        ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/content/imgUpload'
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  created() {
    this.getRolesList()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    getRolesList() {
      this.listLoading = true
      getRolesList().then(response => {
        // console.log(response)
        this.rolesOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      getMenuList({ id }).then(response => {
        // console.log(response.data)
        this.iconList = []
        this.iconList.push({
          name: 'uploadCover' + 0,
          url: response.data.imgs[0]
        })
        this.postForm.id = response.data.id
        this.postForm.name = response.data.name
        this.postForm.url = response.data.url
        this.postForm.icon = response.data.icon
        console.log(this.iconList)
      }).catch(err => {
        console.log(err)
      })
    },
    handleUploadRemove(file) {
      // console.log(file)
      const index = this.iconList.indexOf(file)
      if (index !== -1) {
        this.iconList.splice(index, 1)
        this.postForm.icon = ''
      }
      // console.log(this.iconList)
    },
    handleUploadSucc(res) {
      // console.log(res)
      const url = res.data[0]
      this.postForm.icon = url
      this.iconList.push({
        name: 'uploadIcon',
        url: url
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            editMenu(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑菜单成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addMenu(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加菜单成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .menu-form {
    padding: 40px;
  }
}
</style>
